/*************************************************
   *FileName:      chat.js
   *Description:   聊天.js
   *Others:        陈灿
   *************************************************/
    /*
     * 启动
     */
    mui.init({
        gestureConfig:{
           longtap: true, //默认为false
        } 
    });
    mui.init({
        beforeback: function() {
            var list = plus.webview.currentWebview().opener();
            mui.fire(list, 'refreshindex');
            return true;
        }
    });
    mui('.mui-scroll-wrapper').scroll({
        indicators: false,      //是否显示滚动条 默认为true
        deceleration: 0.003,    //阻尼系数,系数越小滑动越灵敏 默认0.0006
        bounce: true,           //是否启用回弹 默认true
        longtap: true,          //默认为false
    });
    /*
     * 变量初始化
     */
    var that =getUrlParam('thatid');
    var state=getUrlParam('state'),oup;
    var uid = localStorage.replace_uid;
    var token = localStorage.replace_token
    var page = 1,page_num=20,isUp = true;
    var isgifturl='/index.php/api/chat/getGiftList';
    var mygifturl='/index.php/api/chat/getUsersGiftList';
    var odata={ uid: uid,token :token};
    var add_friend_cost = 0;
    var my_friend_cards = 0;
    var my_vip = 0,my_verify = 0;
    var success_date_nums,date_nums,good_nums,bad_nums,complaint_nums,my_date_cards,date_cost,manager_uid,oshedate_status,oparent_uid;
    var upData ={
        type:'',
        msg:'',
        gift_id:'0',
        url:'',
        num:'0',
        thumb:'',
        id:'',
        voice_second:'',
        state:'0',
    }
    var myface,vdo_loging=1,vdo_obj;
    if(localStorage.replace_face=='images/myimg.jpg'){
        myface = localStorage.replace_face;
    }else{
        myface = DOMAIN_NAME+localStorage.replace_face
    }
    /*
     * 主程序
     */ 
    window.addEventListener('chatcard', function(e){//执行刷新
        card();  
    });
    $(document).ready(function() 
    {
        //样式加载
        pagecss();
        connect();
    });

    var server = "http://replace-i.oss-cn-hangzhou.aliyuncs.com/";  //申请到的阿里云OSS地址
                    
    var OSSAccessKeyId= 'LTAIyJPvdRXd1eX9';     //申请到的阿里云AccessKeyId和AccessKeySecret
    var AccessKeySecret= 'Wkwdr687sxx0nK5RfWh5NiETPBAme3';//需要用自己申请的进行替换
    var files = [];  //存储文件信息的数组
    var fname = "";  //表示文件名，例如  XXXX.jpg;
    var dir ="app/";  //指定上传目录，此处指定上传到app目录下
    
    var testName;   //本地测试用的
    /*
     * 阿里云参数设置，用于计算签名signature
     */
    var policyText = {
        "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
        "conditions": [
            ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
        ]
    };
    var policyBase64 = Base64.encode(JSON.stringify(policyText));
    var message = policyBase64;
    var bytes = Crypto.HMAC(Crypto.SHA1, message, AccessKeySecret, {
        asBytes: true
    });
    var signature = Crypto.util.bytesToBase64(bytes);

    //得到文件名的后缀
    function get_suffix(filename) {
        var pos = filename.lastIndexOf('.');
        var suffix = '';
        if(pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    // 拍照添加文件
    function appendByCamera() {
        plus.camera.getCamera().captureImage(function(p) {
            appendFile(p);
        });
    }
    // 从相册添加文件
    function appendByGallery() {
        plus.gallery.pick(function(p) {
            appendFile(p);
        });
    }
    // 添加文件
    var index = 1;

    function appendFile(p) {
        var fe = document.getElementById("files");
        // var li = document.createElement("li");
        // var n = p.substr(p.lastIndexOf('/') + 1);
        // fname = n;
        // li.innerText = n;
        // fe.appendChild(li);
        files.push({
            name: "uploadkey" + index,
            path: p
        });
        index++;
        // empty.style.display = "none";
    }
    /**
     * pagecss
     * 样式加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function pagecss(){
         mui.plusReady(thatinf)
         mui.plusReady(getvoice)
         mui.plusReady(alode)
//      alode()
//      getvoice()
//      thatinf()
        //我的头像
        $('.title-right').html('<em class="title-em"></em><img onerror="imgExists(this)" src="'+myface+'" />') 
        //状态判断
        if(state){
            $('.header-color').append('<a class="chat-addfrand mui-pull-right"></a><a class="complain mui-pull-right" ></a>');
            $('.chat-star').remove();//交互更改     临时聊天没有
            mui.plusReady(chatstate)
            upData.state=''+state+'';
        }else{
            $('.header-color').append('<a class="chat-love mui-pull-right"></a><a class="complain mui-pull-right" ></a>');
            $('.chip-linkbox').css({display:'block'})
            $('.gift-linkbox').css({display:'block'})
        }
        
        $('.chat').on('tap','.complain',function(){
            common.pageTransition("complaint.html?thatid="+that);
        })
        
        $('.chat').on('tap','.chat-left .user',function(){
            common.pageTransition('personal.html?friend_uid='+that)
        })

        $('.chat').on('tap','.link.card',function(){
            common.pageTransition('myfriend.html?that=chat')
        })//选择好友
        
        $('.chat').on('focusin','.chat-val',function(){
            $('.rests').css({display:'none'});
            $('.menu-box').css({display:'none'});
            $('.footer .bth').css({display:'block'});
            $('.mui-link').removeClass('keyboard');
            indown();
            setTimeout(function(){texttoBottom()},350)
        }).on('blur','.chat-val',function(){
            if($('.chat-val').find('img').length==0&&$('.chat-val').text().length==0){
                $('.rests').css({display:'block'});
                $('.footer .bth').css({display:'none'});
            }
        })//键盘按钮显示
        
        
        
//      $('.chat-val').on('longtap',function(){
//          $('#topPopover').removeClass('videobox');
//          $('#topPopover').addClass('pastebox');
//          $('.mui-table-view-cell').html('<a class="paste">粘贴</a>');
//          $(this).attr('id','openPopover');
//          mui('.mui-popover').popover('toggle',document.getElementById("openPopover"));
//          return false;
//      })//弹出复制等按钮
        
//      $('.main').on('tap','.paste',function(){
//          var textgetClipbordText =getClipbordText();
//          $('.chat-val').html(textgetClipbordText);
//      })
        
        $('.box-bot').on('tap','.gift-link',function(){
            $(this).addClass('gift-link-color').siblings('.gift-link').removeClass('gift-link-color');
            $('.box-roll').css({display:'none'});
            $(this).index() == 0 ? $('.gift-lk-box').css({display:'block'}) :$('.chip-lk-box').css({display:'block'});
        })
        
        $('.nub').on('blur',function(){
            if(!parseInt($(this).val())){
                $(this).val(1);
            }
        })
        
        var onub =1;
        $('.nub-box a').on('tap',function(){
            onub=parseInt($(this).siblings('.nub').val());
            if($(this).hasClass('nub-jian')){
                onub==1 ? false : onub--;
            }else{
                onub++;
            }
            $('.nub').val(onub);
        })
    
        $('.main').on('tap','.imgs',function(){//视频和图片查看
            var osrc = $(this).find('img').attr('data-url')
            $('.img-look').addClass('active');
            if($(this).find('.user-img-video').length>0){
                $('.img-look-box').html('<div id="vdo-loding"></div><video class="active" id="media" src="'+osrc+'"></video>')
                $('#media')[0].play(); //播放
                $('#media')[0].addEventListener('canplay',function(){
                    $('#vdo-loding').remove();
                    $('#media').removeClass('active');
                })
            }else{
                $('.img-look-box').html('<img src="'+DOMAIN_NAME+osrc+'"/>')
            }
            return false;
        })
        
        $('.main').on('tap','.card-box',function(){//卡片
            var fid=$(this).find('p.id i').text();
            if(fid!=uid){
                common.pageTransition('personal.html?friend_uid='+fid+'&&chat='+that)
            }else{
                common.pageTransition('personal.html?friend_uid='+fid)
            }
            return false;
        })
        
        $('.img-look').on('tap',function(){
            $(this).removeClass('active');
            if($(this).find('img').length>0){
                $(this).find('img').remove();
            }else{
                $('#media')[0].pause(); //暂停
                $(this).find('video').remove();
            }
        })
        
        $('.gift-box').on('tap','.close',function(){
            $('.gift-box').removeClass('active');
            setTimeout(function(){$('.gift-box').css({display:'none'})},500)
        })
        
        $('.chip-box').on('tap','.close',function(){
            $('.chip-box').removeClass('active');
            setTimeout(function(){$('.chip-box').css({display:'none'})},500)
        })
        
        $('.main').on('tap',function(){
            $('.chat-val').blur();
            $('.mui-link').removeClass('keyboard');
            indown();
            $('.menu-box').css({display:'none'});
            console.log($('.mui-content').height())
        })
        
        $('.chat').on('tap','.mui-link',function(){
            $('.menu-box').css({display:'none'});
            if($(this).hasClass('rests')){
                $('.add').css({display:'block'});
            }else if($(this).hasClass('face')&& !$(this).hasClass('keyboard')){
                $('.chat-val').blur();
                $(this).addClass('keyboard').siblings().removeClass('keyboard');
                $('.keyboard').css({display:'block'});
                $('.menu-face').css({display:'block'});
                $('.mui-slider-indicator .mui-indicator:nth-of-type(1)').addClass('mui-active');
                getface(0,'');
                getface(1,odata);
            }else if($(this).hasClass('voice') && !$(this).hasClass('keyboard')){
                $('.chat-val').blur();
                $(this).addClass('keyboard').siblings().removeClass('keyboard');
                $('.vdo').css({display:'block'});
            }else{
                $(this).removeClass('keyboard');
                $('.face').css({display:'block'});
                $('.chat-val').focus();
                indown();
                return false;
            }
            inup();
            toBottom();
        })//表情等等点击上下
        
        $('.chat').on('tap','.addface',function(){
            var ourl =$('#openPopover').find('img').attr('data-url');
            var thumb =$('#openPopover').find('img').attr('src');
            addface(ourl,thumb,false);
        })
        
        
//      $('.chat .mui-slider').each(function(){
//          console.log(5)
//          var personalImg = $(this).find('.mui-slider-item').length;
//          for (var i=0 ; i<personalImg ;i++) {
//              console.log(55)
//              $(this).find('.mui-slider-indicator').append('<div class="mui-indicator"></div>');
//          }
//          $('.chat .mui-slider-indicator .mui-indicator').eq(0).addClass('mui-active');
//      })//个人首页banner图片的环路以及下标

        $('.chat').on('longtap','.text-box',function(){
            $('#topPopover').removeClass('pastebox');
            $('#topPopover').removeClass('videobox');
            $('#topPopover').removeClass('videobox2');
            if($(this).parents('.chat-box').hasClass('chat-left')){
                if($(this).find('.imgs img').length==0&&$(this).find('.user-img-video').length==0){
                    $('#topPopover').addClass('videobox');
                    $('.mui-table-view-cell').html('<a class="copy">复制</a><a class="delect">删除</a>');
                }else if($(this).find('.user-img-video').length==0){
                    $('#topPopover').addClass('videobox');
                    $('.mui-table-view-cell').html('<a class="addface">添加</a><a class="delect">删除</a>');
                }else{
                    $('#topPopover').addClass('videobox2');
                    $('.mui-table-view-cell').html('<a class="delect">删除</a>');
                }
            }else{
                if($(this).find('.imgs img').length==0&&$(this).find('.user-img-video').length==0){
                    $('.mui-table-view-cell').html('<a class="copy">复制</a><a class="recall">撤回</a><a class="delect">删除</a>');
                }else if($(this).find('.user-img-video').length==0){
                    $('.mui-table-view-cell').html('<a class="addface">添加</a><a class="recall">撤回</a><a class="delect">删除</a>');
                }else{
                    $('#topPopover').addClass('videobox');
                    $('.mui-table-view-cell').html('<a class="recall">撤回</a><a class="delect">删除</a>');
                }
            }
                
            $(this).attr('id','openPopover');
            mui('.mui-popover').popover('toggle',document.getElementById("openPopover"));
        })//弹出复制等按钮
        
        $('.chat .menu').on('tap','.face-bq',function(){
            $('.chat-val').blur();
            var othisimg = $(this).attr("src");
            $('.chat-val').append('<img class="face-bq" src="'+othisimg+'">')
            $('.rests').css({display:'none'});
            $('.footer .bth').css({display:'block'});
            $('.chat-val-box').scrollTop($('.chat-val').height()) //到底
            return false;
        })
        
        $('.circlefriends').on('tap','.dialogue  .face-bq',function(){
            var othisimg = $(this).attr("src");
            var oval = $('.complaint-text').html();
            $('.complaint-text').html(oval+'<img class="face-bq" src="'+othisimg+'">')
            $('.complaint-text').removeClass('active');
        })
        
        $('.chat').on('tap','.reserve',function(){
            $('.chat .mui-bar-nav ~ .mui-content').css({'padding-bottom':'2.5rem'});
            if(!manager_uid){
                mui.alert('该用户没有上级经理人!','提示','确定',null,'div')
                return false;
            }if(manager_uid==uid){
                mui.alert('不能和自己预约!','提示','确定',null,'div')
                return false;
            }else{
                mui.confirm('您是否需要预定？','提示',['确定','取消'],function(e){
                    if(e.index==0){
                        common.pageTransition('chat.html?thatid='+manager_uid+'&&state='+state+'&&up=true')
                    }
                },'div');
            }
            
        })
        
        $('.chat').on('tap','.face-bot a',function(){
            //获得slider插件对象
            $('.menu-face .mui-slider').removeClass('active');
            $(this).addClass('face-bot-color').siblings().removeClass('face-bot-color');
            var oindex = $(this).index();
            
            if(oindex){
                $('.mui-slider-myface').addClass('active');
            }else{
                $('.mui-slider-sitface').addClass('active');
            }
        })
        
        $('.chat').on('tap','.gift-a',function(){
            $(this).addClass('active').siblings().removeClass('active');
        })
        
        $('.chat').on('tap','.add .gift-linkbox',function(){//礼物box弹出
            $('.mui-content').css({'padding-bottom':'2.5rem'});
            $('.menu-box').css({display:'none'});
            $('.box-roll').css({display:'none'});
            $('.gift-box  .gift-link').removeClass('gift-link-color');
            $('.gift-box  .gift-link').eq(0).addClass('gift-link-color');
            $('.gift-box  .gift-lk-box').css({display:'block'});
            giflide(1,isgifturl,1)
            giflide(1,mygifturl,2)
            $('.gift-box').css({display:'block'})
            setTimeout(function(){$('.gift-box').addClass('active')},10)
        })
        
        $('.chat').on('tap','.add .chip-linkbox',function(){//礼物box弹出
            $('.mui-content').css({'padding-bottom':'2.5rem'});
            $('.menu-box').css({display:'none'});
            $('.box-roll').css({display:'none'});
            $('.chip-box  .gift-link').removeClass('gift-link-color');
            $('.chip-box  .gift-link').eq(0).addClass('gift-link-color');
            $('.chip-box  .gift-lk-box').css({display:'block'});
            giflide(2,isgifturl,1);
            giflide(2,mygifturl,2);
            $('.chip-box').css({display:'block'})
            setTimeout(function(){$('.chip-box').addClass('active')},10)
        })
        
        $('.chat').on('tap','.gift-box .btn',function(){//发送礼物
            var oindex =$('.gift-link-color').index();
            var obj = $('.gift-box .box-roll').eq(oindex).find('.active');
            if(obj.length>0){
                oindex==1 ? upData.type='donation_gift' : upData.type='gift' ;
                upData.url=obj.find('img').attr('src');
                upData.msg=obj.find('.gift-name').text();
                upData.gift_id=obj.attr('data-id');
                upData.num=$('.gift-box .nub').val();
                $('.gift-box').removeClass('active');
                setTimeout(function(){$('.gift-box').css({display:'none'})},500)
                uploddata();
            }
        })
        
        $('.chat').on('tap','.chip-box .btn',function(){//发送礼物
            var oindex =$('.gift-link-color').index();
            var obj = $('.chip-box .box-roll').eq(oindex).find('.active');
            if(obj.length>0){
                oindex==1 ? upData.type='donation_pieces' : upData.type='pieces' ;
                upData.url=obj.find('img').attr('src');
                upData.msg=obj.find('.gift-name').text();
                upData.gift_id=obj.attr('data-id');
                upData.num=$('.gift-box .nub').val();
                $('.chip-box').removeClass('active');
                setTimeout(function(){$('.chip-box').css({display:'none'})},500)
                uploddata();
            }
        })
        
        $('.vdo.menu-box .vdo-link').on('tap',function(){
            $(this).addClass('vdo-color').siblings('.vdo-link').removeClass('vdo-color');
            $('.vdo-text').eq($(this).index()).css({display:'block'}).siblings('.vdo-text').css({display:'none'});
        })
        
        $('.mui-scroll-wrapper').on('tap','.copy',function(){
            var txt = $('#openPopover .text p').text();
            setClipbordText(txt);
            popoverhide();
        })//点击复制
        
        $('.chat').on('tap','.mui-backdrop',function(){
            $('#openPopover').removeAttr('id');
        })
        
        $('.footer').on('tap','.bth',function(){//文字发送
            if($('.chat-val').html()){
                upData.type = 'text';
                var otext =$('.chat-val').html();
                otext = otext.replace(/\"/g,".?.");
                upData.msg =otext;
                uploddata();
            }
        })
        
        $('.chat').on('tap','.vdos .vdos-a',function(){
            upData.type = 'voice';
            upData.msg = $(this).text();
            upData.url=$(this).attr('data-voice');
            uploddata();
        })
        
        $('.chat').on('tap','.menu-face .face-img',function(){
            var src = $(this).attr('data-src');
            var src2 = $(this).attr('data-thumb');
            upData.type = 'img';
            upData.thumb = src2;
            upData.url = src;
            uploddata();
        })
        $('.link.phot').on('tap',function(){
            camera(false);
        })
        
        $('.chat').on('tap','.face-add',function(){
            camera(true);
        })
    }
    /**
     * thatinf
     * 好友信息
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function thatinf(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + '/index.php/api/user/othersInfo',
            dataType:'jsonp',
            data: { uid: that},
            success: function(data) {
                if(data.error_code == 0){
                    localStorage.otherface=DOMAIN_NAME+data.data.face;
                    localStorage.othername=data.data.nickname;
                    $('.title-left').html('<em class="title-em"></em><img onerror="imgExists(this)" src="'+localStorage.otherface+'" />');
                    msglode()
                }
            }
        });
    }
    function chatstate(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + '/index.php/api/users_date/dateDetail',
            dataType:'jsonp',
            data: { uid: uid,token:token,id:state},
            success: function(data) {
                console.log(data)
                if(data.error_code == 0){
                    data.data.uid==uid &&data.data.friend_uid==that ?  $('.reserve-linkbox').css({display:'block'})  :null;
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }
            }
        });
    }
    
    function setClipbordText(txt) {
        if(!window.plus) return;
        if(mui.os.android) {
            var Context = plus.android.importClass("android.content.Context");
            var main = plus.android.runtimeMainActivity();
            var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
            plus.android.invoke(clip,"setText",txt);
        } else {
            var UIPasteboard  = plus.ios.importClass("UIPasteboard");
            var generalPasteboard = UIPasteboard.generalPasteboard();
            generalPasteboard.setValueforPasteboardType(txt,"public.utf8-plain-text");
        }
    }
    
    function getClipbordText() {
        if(!window.plus) return;
        if(mui.os.android) {
            var Context = plus.android.importClass("android.content.Context");
            var main = plus.android.runtimeMainActivity();
            var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
            return plus.android.invoke(clip, "getText");
        } else {
            var UIPasteboard = plus.ios.importClass("UIPasteboard");
            var _val=generalPasteboard.plusCallMethod({valueForPasteboardType:"public.utf8-plain-text"});
            return _val || '';
        }
    }
    
    function inup(){
        $('.mui-content').css({'padding-bottom':'15rem'});
    }   
    function indown(){
        $('.mui-content').css({'padding-bottom':'2.5rem'});
    }  
    
    function popoverhide() {
        mui('.mui-popover').popover('toggle');//show hide toggle
        $('.text').removeAttr('id');
    }
    

    //相机
    function camera(sty){
        common.actionSheet('选择上传','取消',[{title:'从相册获取'},{title:'拍照'}],function(index){
            localStorage.camopen="false";
            if(index==1){
                if($('.addVideo').length){
                    mui.toast('不能同时上传图片和视频',{ duration:2000, type:'div' });
                }else{
                    common.galleryImg(function(src){
                        //上传
                        if(sty){
                            upimg(src,'faceimg','true');
                        }else{
                            upimg(src,'img','true');
                        }
                    })
                }
            }else if(index==2){
                if($('.addVideo').length){
                    mui.toast('不能同时上传图片和视频',{ duration:2000, type:'div' });
                }else{
                    common.cameraImg(function(src){
                        if(sty){
                            upimg(src,'faceimg','true');
                        }else{
                            upimg(src,'img','true');
                        }
                    })
                }
            }
        })
    }
    
    //摄像
    $('.link.void').on('tap',function(){
        localStorage.camopen="false";
        common.videoCapture(function(s){
            // upimg(s,'video','true');
            appendFile(s);
            videoUpload();
        });
    })
    /**
     * msglode
     * 聊天记录
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function msglode(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/chat/UsersChatLogs",
            dataType:'jsonp',
            data: { uid: uid,token :token,friend_uid:that,page:page ,page_num:page_num,date_id:upData.state},
            success: function(data) {
                if(data.error_code == 0){
                    console.log(data)
                    oup=data.data.work_unit;
                    manager_uid = data.data.manager_uid;
                    if(data.data.chat){
                        var ohtml ='';
                        if(data.data.chat.length<page_num){
                            if(state){
                                ohtml+='<div class="time-box chat-star"><span class="time">禁止使用低俗、色情、淫秽等内容破坏聊天环境；严禁涉及黄、赌、毒等一切违法行为。</span></div>';   
                            }else if(data.data.introducer){
                                ohtml+='<div class="time-box chat-star"><span class="time">您通过'+data.data.introducer+'的推荐添加了'+data.data.nickname+'为好友，现在可以开始聊天</span></div>';
                            }else{
                                ohtml+='<div class="time-box chat-star"><span class="time">您已添加'+data.data.nickname+'为好友，现在可以开始聊天</span></div>';
                            }
                        
                        }
                        localStorage.chattime=data.data.chat[0].send_time;
                        for(var i=data.data.chat.length-1 ; i>=0 ; i--){
                            var oldtime = i==data.data.chat.length-1 ? 'null'  :data.data.chat[i+1].send_time ;
                            ohtml +=chatubtime(data.data.chat[i].send_time,oldtime);
                            if(data.data.chat[i].type=='text'){//文字
                                var ocontent = data.data.chat[i].content.replace(/\.\?\./g,"'");
                                if(data.data.chat[i].from_uid==uid){
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-right">'
                                           +'<img onerror="imgExists(this)" class="user" src="'+myface+'"/><div class="text-box">'
                                           +'<div class="text"><em class="em"></em><p>'+ocontent+'</p></div></div></div>';
                                }else{
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-left">'
                                           +'<img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/><div class="text-box"><p class="username">'+localStorage.othername+'</p>'
                                           +'<div class="text"><em class="em"></em><p>'+ocontent+'</p></div></div></div>';
                                }
                            }else if(data.data.chat[i].type=='img'){
                                if(data.data.chat[i].from_uid==uid){
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/>'
                                       +'<div class="text-box"><div class="imgs"><img class="img" data-url="'+data.data.chat[i].url+'" data-src="'+data.data.chat[i].thumb+'" src="'+DOMAIN_NAME+data.data.chat[i].thumb+'"/></div></div></div>'
                                }else{
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/>'
                                       +'<div class="text-box"><p class="username">'+localStorage.othername+'</p><div class="imgs">'
                                       +'<img class="img" data-url="'+data.data.chat[i].url+'" data-src="'+data.data.chat[i].thumb+'"  src="'+DOMAIN_NAME+data.data.chat[i].thumb+'"/></div></div></div>'
                                }
                            }else if(data.data.chat[i].type=='video'){
                                if(data.data.chat[i].from_uid==uid){
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/>'
                                       +'<div class="text-box"><div class="imgs"><div class="user-img-video"></div><img class="vdo" data-url="'+data.data.chat[i].url+'" src="'+data.data.chat[i].thumb+'"/></div></div></div>'
                                }else{
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/>'
                                       +'<div class="text-box"><p class="username">'+localStorage.othername+'</p><div class="imgs">'
                                       +'<div class="user-img-video"></div><img class="vdo" data-url="'+data.data.chat[i].url+'" src="'+data.data.chat[i].thumb+'"/></div></div></div>'
                                }
                            }else if(data.data.chat[i].type=='radio'||data.data.chat[i].type=='voice'){//语音
                                var voiceli = data.data.chat[i].type=='voice'? 'video-box-p':'';
                                var owidth = data.data.chat[i].type=='voice'? '':'style="width: '+parseFloat(data.data.chat[i].voice_second)*0.25+'rem;"';
                                var voicetext = data.data.chat[i].type=='voice'? '<p>'+data.data.chat[i].content+'</p>':'<span class="second">'+data.data.chat[i].voice_second+'"</span>';
                                if(data.data.chat[i].from_uid==uid){
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/><div class="text-box">'
                                       +'<div class="video-box '+voiceli+'" '+owidth+' data-radio="'+DOMAIN_NAME+data.data.chat[i].url+'"><em class="em"></em><img class="vidos" src="images/chat_vidos.png"/>'
                                       +voicetext+'</div></div></div>'
                                }else{
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/><div class="text-box">'
                                       +'<p class="username">'+localStorage.othername+'</p><div class="video-box '+voiceli+'" '+owidth+' data-radio="'+DOMAIN_NAME+data.data.chat[i].url+'"><em class="em"></em><img class="vidos" src="images/chat_vidos2.png"/>'
                                       +voicetext+'</div></div></div>'
                                }
                            }else if(data.data.chat[i].type=='share'){//名片
                                if(data.data.chat[i].from_uid==uid){
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/>'
                                       +'<div class="text-box"><div class="card-box"><em class="em"></em>'
                                       +'<p class="card-p">推荐好友</p><img onerror="imgExists(this)" src="'+data.data.chat[i].url+'"/><div>'
                                       +'<p class="name">'+data.data.chat[i].content+'</p><p class="id">ID号：<i>'+data.data.chat[i].gift_id+'</i></p></div></div></div></div>';
                                }else{
                                    ohtml +='<div data-id="'+data.data.chat[i].id+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/>'
                                       +'<div class="text-box"><p class="username">'+data.data.chat[i].content+'</p><div class="card-box"><em class="em"></em>'
                                       +'<p class="card-p">推荐好友</p><img onerror="imgExists(this)" src="'+data.data.chat[i].url+'"/><div>'
                                       +'<p class="name">'+data.data.chat[i].content+'</p><p class="id">ID号：<i>'+data.data.chat[i].gift_id+'</i></p></div></div></div></div>';
                                }
                            }else if(data.data.chat[i].type=='gift'||data.data.chat[i].type=='pieces'||data.data.chat[i].type=='donation_gift'||data.data.chat[i].type=='donation_pieces'){//礼物
                                var otitle = data.data.chat[i].from_uid==uid ? '你向 '+localStorage.othername+' 打赏了' : localStorage.othername+' 向你打赏了'
                                ohtml +='<div class="chat-card"><a class="card text-box" ><p>'+otitle+'</p>'
                                       +'<div class="card-con"><img onerror="imgExists(this)" src="'+data.data.chat[i].url+'"/><div class="card-text"><p>'+data.data.chat[i].content+'</p><span>x'+data.data.chat[i].num+'</span></div></div></a></div>';
                            }
                        }
                        $('.main-box').prepend(ohtml);
                        if(page==1){
                            toBottom();
                            $('.imgs').each(function(){
                                $(this).find('img').load(function(){toBottom()})
                            })
                        }else{
                            scrollTop = common.getTop($('#loging')[0]);
                            $('.main').scrollTop(scrollTop) 
                        }
                        $('.main-box').children('#loging').remove(); 
                        isUp = true
                    }else if(page==1&&data.data.chat==''){
                        if(getUrlParam('state')!=null){
                            $('.main .main-box').html('<div class="time-box chat-star"><span class="time">禁止使用低俗、色情、淫秽等内容破坏聊天环境；严禁涉及黄、赌、毒等一切违法行为。</span></div>');   
                            if(getUrlParam('up')){
                                var oscontent = '您好，我是'+oup+'场所经理，很高兴为您服务！';
                                var date_id =upData.state;
                                $.ajax({
                                    type: "post",
                                    url: DOMAIN_NAME + '/index.php/api|chat/addchat',
                                    dataType:'jsonp',
                                    data: { uid: uid,token:token,from_uid:that,to_uid:uid,content:oscontent,date_id:date_id},
                                    success: function(data) {
                                        if(data.error_code == 0){
                                            $('.main-box').append('<div data-id="'+data.id+'" class="chat-box chat-left">'
                                               +'<img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/><div class="text-box"><p class="username">'+localStorage.othername+'</p>'
                                               +'<div class="text"><em class="em"></em><p>'+oscontent+'</p></div></div></div>')
                                        }
                                    }
                                });
                            }
                        }else if(data.data.introducer){
                            $('.main .main-box').html('<div class="time-box chat-star"><span class="time">您通过'+data.data.introducer+'的推荐添加了'+data.data.nickname+'为好友，现在可以开始聊天</span></div>');
                        }else{
                            $('.main .main-box').html('<div class="time-box chat-star"><span class="time">您已添加'+data.data.nickname+'为好友，现在可以开始聊天</span></div>');
                        }
                    
                    }
                    else{
                        $('.main').find('#loging').text('已经到顶了').addClass('ovr');
                        isUp = false;
                    }
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    
                }
            }
        });
    }
    $('.main').on('scroll',function(){//监听滚动
        var scroll_top = $('.main').scrollTop();
        var doc_height = $('.main').height();
        if(scroll_top <= 0 && isUp==true){
            $('.main-box').prepend('<div id="loging"></div>')
            page++;
            isUp=false;
            setTimeout(function(){msglode()},500);
        }
    })
    /**
     * 
     * 语音播放
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    var p =null;
    var oarr=common.browserType();
    $('.chat').on('tap','.video-box',function(){
        var vic = $(this).attr('data-radio');
        if(oarr.ios){ 
            if(p != null){
                p.stop();
            }
            var dtask = plus.downloader.createDownload(vic, {}, function ( d, status ) {
            // 下载完成
                if ( status == 200 ) { 
                    if ( plus.audio == undefined ) {
                        alert( "Device not ready!" );
                    }
                    p = plus.audio.createPlayer(d.filename);
                    p.play( function () {
                        p = null;
                    }, function ( e ) {
                       plus.nativeUI.toast("播放错误: " + e.message);
                    });
                    
                } else {
                    alert( "网络错误"); 
                }  
            });
            dtask.start();                  
        }else{
            common.playAudio(vic);
        }
    })//语音播放
    /**
     * giflide
     * 系统礼物列表
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function giflide(type,ourl,sort){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + ourl,
            dataType:'jsonp',
            data: { uid: uid,token :token,type:type},
            success: function(data) {
                if(data.error_code == 0){
                    console.log(data)
                    var olistg = '<div class="mui-slider-item mui-active">';
                    for(var i=0 ; i<data.data.length; i++){
                        if(i%8==0&&i!=0){
                            console.log(i)
                            olistg+='</div><div class="mui-slider-item">';
                        }
                        if(sort==1){
                            olistg+='<a class="gift-a" data-id="'+data.data[i].id+'"><p class="img-p"><img onerror="imgExists(this)" src="'+DOMAIN_NAME+data.data[i].url+'"/></p><p class="gift-name">'+data.data[i].name+'</p><p class="gift-nub">'+parseInt(data.data[i].money)+'换币</p></a>';
                        }else{
                            olistg+='<a class="gift-a" data-id="'+data.data[i].gift_id+'"><p class="img-p"><img onerror="imgExists(this)" src="'+DOMAIN_NAME+data.data[i].url+'"/></p><p class="gift-name">'+data.data[i].name+'</p><p class="gift-nub">X'+data.data[i].total+'</p></a>';
                        }
                    }
                    if(type==1 && sort==1 ){
                        $('.gift-box .gift-lk-box .mui-slider-group').html(olistg+'</div>')
                    }else if(type==1 && sort==2 ){
                        $('.gift-box .chip-lk-box .mui-slider-group').html(olistg+'</div>')
                    }else if(type==2 && sort==1 ){
                        $('.chip-box .gift-lk-box .mui-slider-group').html(olistg+'</div>')
                    }else{
                        $('.chip-box .chip-lk-box .mui-slider-group').html(olistg+'</div>')
                    }
                    mui(".mui-slider").slider({interval: 0});
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    sort==1 ? $('.gift-lk-box').html('') :  $('.chip-lk-box').html('');
                }
            }
        });
    }
    /**
     * getvoice
     * 个性语音列表
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function getvoice(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + '/index.php/api/chat/getPersonalityVoicesList',
            dataType:'jsonp',
            data: { uid: uid,token :token},
            success: function(data) {
                if(data.error_code == 0){
                    var ohtml='<div class="mui-slider-item">';
                    var oli ='';
                    for(var i=0 ; i<data.data.length; i++){
                        if((i%10==0)&&(i!=0)){
                            ohtml+='</div><div class="mui-slider-item">';
                            oli+='<div class="mui-indicator"></div>';
                        }
                        ohtml+='<a class="vdos-a" data-voice="'+data.data[i].name+'">'+data.data[i].content+'</a>';
                    }
                    ohtml+='</div>';
                    $('.vdos .mui-slider-group').html(ohtml);
                    $('.vdos .mui-slider-indicator').html('<div class="mui-indicator mui-active"></div>'+oli+"");
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                }
                mui(".mui-slider").slider({interval: 0});
            }
        });
    }
    /**
     * getvoice
     * 表情
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function getface(sys,odata){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/chat/getSystemExpressionsList' ,
            dataType:'jsonp',
            data: odata,
            success: function(data) {
                var ohtml='';
                var oli ='';
                if(data.error_code == 0){
                    ohtml+='<div class="mui-slider-group"><div class="mui-slider-item">';
                    for(var i=0 ; i<data.data.length; i++){
                        if(sys==0){
                            if((i%21==0)&&(i!=0)){
                                ohtml+='</div><div class="mui-slider-item">';
                                oli+='<div class="mui-indicator"></div>';
                            }
                            ohtml+='<a data-id="'+data.data[i].id+'"><img class="face-bq" src="'+DOMAIN_NAME+data.data[i].url+'"></a>';
                        }else{
                            if(((i+1)%10==0)&&(i!=0)){
                                ohtml+='</div><div class="mui-slider-item">';
                                oli+='<div class="mui-indicator"></div>';
                            }else if((i==0)&&(sys==1)){
                                ohtml+='<a class="face-add"><img src="images/chat_add.png"></a>';
                            }
                            ohtml+='<a data-id="'+data.data[i].id+'" ><img class="face-img" data-src="'+data.data[i].url+'"  data-thumb="'+data.data[i].url+'" src="'+DOMAIN_NAME+data.data[i].url+'"></a>';
                        }
                    }
                    ohtml+='</div></div><div class="mui-slider-indicator"><div class="mui-indicator mui-active"></div>'+oli+'</div></div>';
                    sys==0? $('.mui-slider-sitface').html(ohtml): $('.mui-slider-myface').html(ohtml);
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    sys==0? $('.mui-slider-sitface').html(''): $('.mui-slider-myface').html('<div class="mui-slider-group"><div class="mui-slider-item"><a class="face-add"><img src="images/chat_add.png"></a></div></div><div class="mui-slider-indicator"><div class="mui-indicator mui-active"></div></div>');
                }
                mui(".mui-slider").slider({interval: 0});
            }
        });
    }
    /**
     * 
     * 发送消息
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    
    function uploddata(){
        console.log(JSON.stringify('{"type":"chat","from_user":"'+uid+'","to_user":"'+that+'","data":{"type":"'+upData.type+'","thumb":"'+upData.thumb+'","date_id":"'+upData.state+'","msg":"'+upData.msg+'","gift_id":"'+upData.gift_id+'","url":"'+upData.url+'","num":"'+upData.num+'","voice_second":"'+upData.voice_second+'"}}')) 
        ws.send('{"type":"chat","from_user":"'+uid+'","to_user":"'+that+'","data":{"type":"'+upData.type+'","thumb":"'+upData.thumb+'","date_id":"'+upData.state+'","msg":"'+upData.msg+'","gift_id":"'+upData.gift_id+'","url":"'+upData.url+'","num":"'+upData.num+'","voice_second":"'+upData.voice_second+'"}}');
    }
    /**
     * 
     * 上传图片,语音，视频
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function videoUpload() {    //视频上传
        if(files.length <= 0) {
            plus.nativeUI.alert("没有添加上传文件！");
            return;
        }
        // common.loadingIn();
        // mui.toast('开始上传：',{ duration:2000, type:'div' });
        // outSet("开始上传：")

        // var wt = plus.nativeUI.showWaiting();
        var task = plus.uploader.createUpload(server, {
                method: "POST"
            },
            function(t, status) { //上传完成
                console.log("t" + JSON.stringify(t));
                if(status == 200) {
                    mui.toast('上传成功',{ duration:2000, type:'div' });
                    // outLine("上传成功：" + t.responseText);
                    //至此上传成功，上传后的图片完整地址为server+testName
                    var uploaderFileObj = {
                        "server":server,
                        "path":testName
                    };
                    files = [];
                    console.log(t.responseText);
                    plus.storage.setItem("uploader", JSON.stringify(uploaderFileObj));
                    console.log(uploaderFileObj.path);
                    upData.url = 'https://replace-o.oss-cn-hangzhou.aliyuncs.com/'+uploaderFileObj.path;
                    upData.thumb = 'http://replace-o.oss-cn-hangzhou.aliyuncs.com/'+uploaderFileObj.path+'?x-oss-process=video/snapshot,t_1,f_jpg,w_0,h_0,m_fast';
                    upData.type='video';
                    videoTransCode(uploaderFileObj.path);
                    
                    // var w = plus.webview.create("uploader_ret.html", "uploader_ret.html", {
                    //     scrollIndicator: 'none',
                    //     scalable: false
                    // });
                    // w.addEventListener("loaded", function() {
                        // wt.close();
                        // w.show("slide-in-right", 300);
                    // }, false);
                } else {
                    mui.toast('上传失败：' + status,{ duration:2000, type:'div' });
                }
            }
        );
        var suffix1 = get_suffix(fname);  //文件后缀  例如   .jpg
        var keyname = dir + new Date().getTime() + suffix1;
        testName = keyname;
        
        //按照之前说明的参数类型，按顺序添加参数
        task.addData("key", keyname);
        task.addData("policy", policyBase64);
        task.addData("OSSAccessKeyId", OSSAccessKeyId);
        task.addData("success_action_status", "200");
        task.addData("signature", signature);
        var f = files[0];
        var filename=files[0].path;
        var index1=filename.lastIndexOf("."); 
        var index2=filename.length;
        var index3=filename.lastIndexOf("?"); 
        if(index3 > 0){
            var postf=filename.substring(index1+1,index3);//后缀名 
        }else{
            var postf=filename.substring(index1+1,index2);//后缀名 
        }
        
        // alert(postf);
        task.addFile(f.path, {
            key: "file",
            name: "file",
            mime: "video/"+postf
        });

        task.start();
    }

    function videoTransCode(video_url){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/chat/videoTransCode' ,
            dataType:'jsonp',
            data: {url:video_url},
            success: function(data) {
                if(data.error_code == 0){
                    uploddata();
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                }
            }
        });
    }

    function upimg(src,type,state){
        var task = plus.uploader.createUpload(DOMAIN_NAME + "/index.php/api/chat/fileUpload",
        { method:"POST",blocksize:20480,priority:100 },
            function (t, status) { //上传完成
                common.loadingOut();
                if (status == 200) {
                    if(state=='true'){
                        var ad =t.responseText;
                        var b=/\"file\"\:\"([^]*?)\"\,/;
                        var c=/\"thumb\"\:\"([^]*?)\"\}\)/;
                        var s=ad.match(b);
                        upData.url = s[1];
                        var h= ad.match(c);
                        upData.thumb = h[1];
                    }else{
                        upData.url = src;
                        upData.thumb = state;
                    }
                    type=='faceimg' ? addface(upData.url,upData.thumb,true):uploddata() ;
                }else{ 
                    mui.toast('上传失败',{ duration:2000, type:'div' });
                }
            }
        );
        common.loadingIn();
        if(type=='img'){
            task.addFile(src, {key: "image"}); 
        }else if(type=='faceimg'){
            task.addFile(src, {key: "faceimg"});
        }else if(type=='video'){
            task.addFile(src, {key: "video"});
        }else if(type=='radio'){
            task.addFile(src, {key: "radio"});
        }
        upData.type=type;
        task.start();
    }
    /**
     * 
     * 发送语音
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    var moveEndY = 0;
    var startY = 0;
    var r = null; 
    function chatRecord() {
        plus.device.vibrate( 500 );
        localStorage.startTime = (new Date()).valueOf();
        r = plus.audio.getRecorder(); 
        if ( r == null ) {
            plus.nativeUI.toast( "Device not ready!" );
            return; 
        } 
        r.record( {filename:"_doc/audio/",format: "amr"}, function (path) {
            if(localStorage.record == 'send'){
                var amrtime =parseInt((localStorage.endTime - localStorage.startTime)/1000);
                if(amrtime > 1 ){
                    upData.voice_second = amrtime;
                    upimg(path,'radio','true');
                    localStorage.record = 'cancel';
                }else{
                    plus.nativeUI.toast('语音时间太短');
                }
            }
        }, function ( e ) {
            $('.voice-lading').css({display:'none'});
        } );
    }
    function stopChatRecord() {
        localStorage.endTime = (new Date()).valueOf();
        localStorage.record = 'send';
        r.stop(); 
    }
    function cancelRecord(e){
        localStorage.endTime = (new Date()).valueOf();
        localStorage.record = 'cancel';
        r.stop(); 
    }
    //按住说话
    $(".vdo-a").on("touchstart", function(e) {
        $('.voice-lading').css({display:'block'});
        e.preventDefault();
        //按下时手指坐标
        startY = e.originalEvent.changedTouches[0].pageY;
        chatRecord();
    });
    $(".vdo-a").on('touchend', function(e) {
        //松开时手指坐标
        $('.voice-lading').css({display:'none'});
        moveEndY = e.originalEvent.changedTouches[0].pageY;
        Y = startY - moveEndY;
        //取消录音
        if(Y>20){
            cancelRecord()
            return false;
        }else{
            stopChatRecord()
        }
    })
//时间计算
    
    //置地
    function toBottom() {
        $('.main').scrollTop($('.main-box').height()) ;
    }
    
    function texttoBottom() {
        $(".main").css('-webkit-overflow-scrolling','auto'); 
        $('.main').scrollTop($('.main-box').height()-$('.mui-content').height()+$('.footer').height());
        $(".main").css('-webkit-overflow-scrolling','touch');
    }
    
    /**
     * 
     * 好友卡
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function card(){
        upData.type = 'share';
        upData.url=localStorage.getItem('shareurl');
        upData.msg=localStorage.getItem('sharename');
        upData.gift_id=localStorage.getItem('shareid');
        uploddata();
    }
    /**
     * 
     * 撤回
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    $('.chat').on('tap','.recall',function(){
        upData.type='invoke';
        upData.id=$('#openPopover').parents('.chat-box').attr('data-id');
        ws.send('{"type":"invoke","from_user":"'+uid+'","to_user":"'+that+'","data":{"type":"invoke","id":"'+upData.id+'"}}');
        popoverhide();
    })
    /**
     * 
     * 删除
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    $('.chat').on('tap','.delect',function(){
        var oid =$('#openPopover').parents('.chat-box').attr('data-id');
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/chat/chatDel' ,
            dataType:'jsonp',
            data: {uid:uid,token:token,id:oid},
            success: function(data) {
                if(data.error_code == 0){
                    $('#openPopover').parents('.chat-box').prev('.time-box').remove();
                    $('#openPopover').parents('.chat-box').remove();
                    popoverhide();
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                }
            }
        });
    })
    /**
     * 
     * 添加表情
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function addface(ourl,thumb,opp){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME +'/index.php/api/chat/expressionAdd' ,
            dataType:'jsonp',
            data: {uid:uid,token:token,url:ourl,thumb:thumb},
            success: function(data) {
                if(data.error_code == 0){
                    popoverhide(); 
                    if(opp){
                        $('.mui-link').removeClass('keyboard');
                        indown();
                        $('.menu-box').css({display:'none'});
                    }
                    mui.toast('添加成功！');
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                }
            }
        });
    }
    /**
     * 
     * 发起约会
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    $('.chat').on('tap','.chat-love',function(){
        if(oshedate_status!='3'){
            mui.toast('对方还未通过约会认证',{ duration:2000, type:'div' });
            return false;
        }
        mui.confirm('<span class="yuyue-color">成功约会：<em class="yh">'+success_date_nums+'次</em></span><span class="yuyue-color">收到的约会：<em class="yh">'+date_nums+'次</em></span><span class="yuyue-color">被赞次数：<em class="yh">'+good_nums+'次</em></span><span class="yuyue-color">被差评次数：<em class="yh">'+bad_nums+'次</em></span><span class="yuyue-color">被投诉次数：<em class="yh">'+complaint_nums+'次</em></span><span class="yuyue-color"></span>','约会信用',['约会','取消'],function(e){
            if(e.index == 0){
                var em = ''
                var method = '';
                if(my_date_cards >= date_cost){
                    em = '需支付约会卡：<em class="gift-yhk"></em>X'+date_cost;
                    method = 'cards';
                }else{
                    em = '需支付换币：<em class="gift-jb"></em>X'+date_cost;
                    method = 'balance';
                }
                mui.confirm('您将对'+localStorage.othername+'发起约会，<br />'+em,'发起约会',['支付','取消'],function(e1){
                    if(e1.index == 0){
                        common.loadingIn();
                        $.ajax({
                            type: "post",
                            url: DOMAIN_NAME + "/index.php/api/users_date/dateAdd",
                            dataType:'jsonp',
                            data: { uid: uid, token: token, friend_uid: that, method: method },
                            success: function(data) {
                                common.loadingOut();
                                if(data.error_code == 0){
                                    my_date_cards = data.my_date_cards;
                                    mui.toast('约会申请已发送，等待对方确认！',{ duration:2000, type:'div' });
                                }else if(data.error_code == 1001){
                                    setTimeout(function(){
                                        exitlogin();
                                    },1000);
                                }else{
                                    setTimeout(function(){
                                        mui.confirm('余额不足，请充值!','提示',['充值','取消'],function(e2){
                                            if(e2.index == 0){
                                                common.pageTransition('recharge.html');
                                            }
                                        },'div');
                                    },300)
                                }
                            }
                        });
                    }
                },'div');
            }
        },'div');
    })
    /**
     * alode
     * 卡片加载
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */
    function alode(){
        $.ajax({
            type: "post",
            url: DOMAIN_NAME + "/index.php/api/users_date/dateinfo",
            dataType:'jsonp',
            data: { uid: uid, token: token, friend_uid: that },
            success: function(data) {
                if(data.error_code == 0){
                    my_friend_cards = data.data.my_friend_cards;
                    data.data.success_date_nums ? success_date_nums = data.data.success_date_nums :success_date_nums='0' ;
                    data.data.date_nums ? date_nums = data.data.date_nums :date_nums = '0';
                    data.data.good_nums ? good_nums = data.data.good_nums :good_nums = '0';
                    data.data.bad_nums ? bad_nums = data.data.bad_nums :bad_nums = '0';
                    data.data.complaint_nums ? complaint_nums = data.data.complaint_nums : complaint_nums='0';
                    my_date_cards = data.data.my_date_cards;
                    add_friend_cost = data.data.add_friend_cost;
                    my_vip = data.data.my_vip;
                    my_verify = data.data.my_verify;
                    date_cost = data.data.date_cost;
                    oshedate_status=data.data.date_status;
                }else if(data.error_code == 1001){
                    setTimeout(function(){
                        exitlogin();
                    },1000);
                }else{
                    mui.toast(data.error_msg,{ duration:2000, type:'div' });
                }
            }
        }); 
    }
     /**
     * 
     * 添加朋友
     * @cc 
     * @DateTime 2018-01-08T06:19:16+0800
     * @param    int        
     * @return   void
     */   
    $('.chat').on('tap','.chat-addfrand',function(){
        var em = ''
        var method = '';
        var confirm = '';
        if(my_friend_cards){
            em = '您有好友卡 <em class="gift-hyk"></em> ×'+my_friend_cards+'，<br/>是否使用？';
            method = 'cards'
            confirm = '使用';
        }else{
            em = '您将添加'+localStorage.othername+'为好友，<br/>需支付换币： <em class="gift-jb"></em> ×'+add_friend_cost;
            method = 'balance';
            confirm = '支付';
        }
        mui.confirm(em,'提示',[confirm,'取消'],function(e){
            if(e.index == 0){
                common.loadingIn()
                $.ajax({
                    type: "post",
                    url: DOMAIN_NAME + "/index.php/api/friends_apply/friendsApplyAdd",
                    dataType:'jsonp',
                    data: { uid: uid, token: token, friend_uid: that, method: method },
                    success: function(data) {
                        common.loadingOut()
                        if(data.error_code == 0){
                            my_date_cards = data.my_date_cards;
                            mui.toast('好友申请已发送，等待对方确认！',{ duration:2000, type:'div' });
                        }else if(data.error_code == 1001){
                            setTimeout(function(){
                                exitlogin();
                            },1000);
                        }else{
                            setTimeout(function(){
                                mui.confirm(data.error_msg,'提示',['确定','取消'],function(e2){

                                },'div');
                            },300)
                        }
                    }
                });
            }
                
        },'div');
            
    })

    
/**
   * 
   * 显示信息
   * @cc 
   * @DateTime 2018-01-08T06:19:16+0800
   * @param    int        
   * @return   void
   */
function sendMsg(obj,onmsgtime) {
    console.log('显示信息')
    var objType = obj.type; 
    var sender= obj.sender; 
    onmsg=obj.onmsgtime;
    if(objType=='text'){//文字
        var ocontent = obj.content.replace(/\.\?\./g,"'");
        if(sender){
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-right">'
                   +'<img onerror="imgExists(this)" class="user" src="'+myface+'"/><div class="text-box">'
                   +'<div class="text"><em class="em"></em><p>'+ocontent+'</p></div></div></div>';
        }else{
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-left">'
                   +'<img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/><div class="text-box"><p class="username">'+localStorage.othername+'</p>'
                   +'<div class="text"><em class="em"></em><p>'+ocontent+'</p></div></div></div>';
        }
    }else  if(objType=='img'){
        if(sender){
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/>'
               +'<div class="text-box"><div class="imgs"><img onerror="imgExists(this)" class="img" data-url="'+obj.url+'" data-src="'+obj.thumb+'" src="'+DOMAIN_NAME+obj.thumb+'"/></div></div></div>'
        }else{
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/>'
               +'<div class="text-box"><p class="username">'+localStorage.othername+'</p><div class="imgs">'
               +'<img onerror="imgExists(this)" class="img" data-url="'+obj.url+'" data-src="'+obj.thumb+'"  src="'+DOMAIN_NAME+obj.thumb+'"/></div></div></div>'
        }
    }else  if(objType=='video'){
        vdo_loging=vdo_loging+1;
        vdo_obj='.vdo-loging'+(vdo_loging);
        if(sender){
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/>'
               +'<div class="text-box"><div class="imgs"><div class="user-img-video"></div><img onerror="chatimgExists(this)" class="vdo vdo-loging'+vdo_loging+'" data-url="'+obj.url+'" data-src="'+obj.thumb+'" src="'+obj.thumb+'"/></div></div></div>'
        }else{
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/>'
               +'<div class="text-box"><p class="username">'+localStorage.othername+'</p><div class="imgs">'
               +'<div class="user-img-video"></div><img onerror="chatimgExists(this)" class="vdo vdo-loging'+vdo_loging+'" data-url="'+obj.url+'" data-src="'+obj.thumb+'" src="'+obj.thumb+'" /></div></div></div>'
        }
        
    }else if(objType=='radio'||objType=='voice'){//语音
        var voiceli = objType=='voice'? 'video-box-p':'';
        var owidth = objType=='voice'? '':'style="width: '+parseFloat(obj.amrtime)*0.25+'rem;"';
        var voicetext = objType=='voice'? '<p>'+obj.content+'</p>':'<span class="second">'+obj.amrtime+'"</span>';
        if(sender){
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-right"><img onerror="imgExists(this)" class="user" src="'+myface+'"/><div class="text-box">'
               +'<div class="video-box '+voiceli+'" '+owidth+' data-radio="'+obj.url+'"><em class="em"></em><img onerror="imgExists(this)" class="vidos" src="images/chat_vidos.png"/>'
               +voicetext+'</div></div></div>'
        }else{ 
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box chat-left"><img onerror="imgExists(this)" class="user" src="'+localStorage.otherface+'"/><div class="text-box">'
               +'<p class="username">'+localStorage.othername+'</p><div class="video-box  '+voiceli+'" '+owidth+' data-radio="'+obj.url+'"><em class="em"></em><img class="vidos" src="images/chat_vidos2.png"/>'
               +voicetext+'</div></div></div>'
        }
    }else if(objType=='share'){//名片
        var osit = sender? 'chat-right' : 'chat-left';
        var oshareface = sender? myface : localStorage.otherface;
        var osharename = sender? '': '<p class="username">'+localStorage.othername+'</p>' ;
            onmsg +='<div data-id="'+obj.textid+'" class="chat-box '+osit+'"><img onerror="imgExists(this)" class="user" src="'+oshareface+'"/>'
               +'<div class="text-box">'+osharename+'<div class="card-box"><em class="em"></em>'
               +'<p class="card-p">推荐好友</p><img onerror="imgExists(this)" src="'+obj.face+'"/><div>'
               +'<p class="name">'+obj.name+'</p><p class="id">ID号：<i>'+obj.friendid+'</i></p></div></div></div></div>';
    }else if(objType=='gift'||objType=='pieces'||objType=='donation_gift' ||objType=='donation_pieces'){//礼物
        var otitle = sender ? '你向 '+localStorage.othername+' 打赏了' : localStorage.othername+' 向你打赏了'
        onmsg +='<div class="chat-card"><a class="card text-box" ><p>'+otitle+'</p>'
               +'<div class="card-con"><img onerror="imgExists(this)" src="'+obj.giftUrl+'"/><div class="card-text"><p>'+obj.giftname+'</p><span>x'+obj.giftNum+'</span></div></div></a></div>';
    }else if(objType=='invoke'){
        $('.chat-box').each(function(){
            if($(this).attr('data-id')==obj.id){
                if(sender){
                    $(this).prev('.time-box').html('<span class="time">你撤回了一条消息</span>');
                }else{
                    $(this).prev('.time-box').html('<span class="time">对方撤回了一条消息</span>');
                }
                $(this).remove(); 
            }
        })
    }
    console.log(onmsg)
    $('.chat .main-box').append(onmsg);
    if(sender){
        $('.chat-val').text(''); 
    }
    if(objType=='video'){
        vdolazing($(vdo_obj));
    }
    
    setTimeout(function(){$('.main').scrollTop($('.main-box').height()) ;},350)
    onmsg='';
}

function vdolazing(obj){
    setTimeout(function(){
        var ovdo_objsrc=obj.attr('data-src');
        obj.attr('src',ovdo_objsrc);
        obj.load(function(){
            if(obj.attr('src')=='images/vdo_loading.gif'){
                vdolazing($(this));
            }else{
                $('.main').scrollTop($('.main-box').height()) ;
            }
        })
    },500)
}

